#!/usr/bin/perl

##############################################################
#
#Purpose: To update a set of binaries into a set of planetlab nodes
#
#Usage: update.pl
#		-h <host_file>
#		-f <file containing list of files/dirs to be transferred>
#		-p <path in planetlab node>
#		-u <user name>
#
##############################################################

use strict 'vars';
package main;

use Getopt::Std;

use vars qw($opt_h $opt_f $opt_u $opt_p);

my $ssh_options = "-o \"ConnectTimeout=20\"";

#get command line options
getopts('f:h:u:p:');
if ($opt_h eq "" || $opt_f eq "" || $opt_p eq "") {
    die "Usage: pl_put.pl -h <host_file> -f <bin_list_file> -u <username> -p <path>\n";
}
if ($opt_u eq "") {
    $opt_u = "ucb_i3";
}

#concatenate file/dir names
my $fname, my $fnamelist = "";
open (LISTFILE, $opt_f) || die "Cannot open list of files\n";
while ($fname = <LISTFILE>) {
    chomp $fname;
    if ($fname =~ /^\s*#/) {
	print "Ignoring comment - $fname\n";
    } else {
	$fnamelist = $fnamelist." ".$fname;
    }
}

#go over the list of hosts
my %hosts = (), my $host;
open (HOSTFILE, $opt_h) || die "Cannot open host file\n";
while ($host = <HOSTFILE>) {
    chomp $host;
    if ($host =~ /^\s*#/) {
	print "Ignoring comment - $host\n";
    } else {
	$hosts{$host} = 1;
    }
}

#scp
my $i = 0;
foreach $host(keys %hosts) {

    $host =~ s/^\s+//;  #trim whitespace at beginning
    $host =~ s/\s+$//;  #trim whitepsace at end

    $i++;
    print $host."\n";
    my $cmd;
	
    $cmd = "ssh $ssh_options $opt_u\@$host \"mkdir $opt_p\" ";
    print $cmd."\n";
    system($cmd);

    $cmd = "scp -r $ssh_options $fnamelist $opt_u\@$host:$opt_p/";
    print $cmd."\n";
    system($cmd);
    print "\n";

    if ($i % 10 == 0) {
	#sleep 10;
    }
}

#sleep 120;
